/**
 * Author: Erchoc(erchoc@163.com)
 * Date: 2019/3/14
 * Desc: Application Entrypoint
 */
const path = require('path');

const Koa = require('koa');
const Router = require('koa-router');
const Redis = require('ioredis');
const uuidv4 = require('uuid/v4');
const views = require('koa-views');
const server = require('koa-static');
const bodyparser = require('koa-bodyparser');

const config = require('./config');

const app = new Koa();
const router = new Router();
const redis = new Redis(config.redis);

// 错误处理
app.use(async(ctx, next) => {
  try {
    await next();
  } catch (err) {
    console.log(err);
    ctx.status = 200;
    ctx.body = JSON.stringify({
      err_code: 10001,
      err_type: 'unknown_system_router',
      err_info: 'params_decode_failed',
    });
  }
});

// 静态文件加载
app.use(server(__dirname + '/public'));

// 使用模板引擎
app.use(views(path.join(__dirname, '/views'), {
  map: { html: 'ejs' },
}));

// 请求体解析
app.use(bodyparser({
  detectJSON: ctx => {
    return /\.json$/i.test(ctx.path);
  },
  extendTypes: {
    json: ['application/x-javascript'],
  },
  onerror: (err, ctx) => {
    console.log(err);
    ctx.status = 200;
    ctx.body = JSON.stringify({
      err_code: 10002,
      err_type: 'params_decode_failed',
      err_info: 'request body has some wrong',
    });
  },
}));

// 日志和响应时间
app.use(async(ctx, next) => {
    const start_time = console.time('time');
    await next();
    console.timeEnd('time') - start_time;
    console.log(`${ctx.method} - ${ctx.response.status} - ${ctx.url}`)
});



// 应用程序统一入口
app.use(async(ctx, next) => {
  await next();
  ctx.status = 200;
});

// Please visit http://ip:port/yangxj for example
router.get('/:user', async (ctx, next) => {
    const user = ctx.params.user;
    const arr = await redis.hgetall(`user:${user}`);
    const data = {};
    data.list = JSON.parse(JSON.stringify(arr))
    data.title = `${user} 数据列表页`;
    return await ctx.render('list.html', { data });
});

// 路由中间件
app.use(router.routes());
app.use(router.allowedMethods());

module.exports = app.listen(config.port, () => {
    console.log(`Listening on http://localhost:${config.port}`)
})
